"""
侧边栏组件模块 - 提供应用程序侧边栏
"""

import streamlit as st
import pandas as pd
from typing import Dict, Optional, Any

from FDAS.config.settings import (
    DEFAULT_STOCK_CODE,
    DEFAULT_STOCK_NAME,
    DEFAULT_ANALYSIS_TYPE,
    DEFAULT_TIME_RANGE,
    ADJUST_METHODS,
    DATA_PERIODS
)
from FDAS.data import repository
from FDAS.data.constants import (
    ASSET_TYPE_STOCK,
    ASSET_TYPE_FUTURE,
    ASSET_TYPE_OPTION,
    ASSET_TYPE_FUND,
    ASSET_TYPE_INDEX,
    ASSET_TYPE_ETF
)

def create_sidebar() -> Optional[Dict[str, Any]]:
    """
    创建侧边栏组件
    
    返回:
        包含用户选择的参数的字典，如果用户未完成选择则返回None
    """
    with st.sidebar:
        st.header("分析设置")
        
        # 资产类型选择
        asset_type = st.selectbox(
            "选择资产类型:",
            [
                "股票", 
                "期货", 
                "期权", 
                "基金", 
                "指数", 
                "ETF"
            ],
            index=0
        )
        
        # 资产类型映射
        asset_type_map = {
            "股票": ASSET_TYPE_STOCK,
            "期货": ASSET_TYPE_FUTURE,
            "期权": ASSET_TYPE_OPTION,
            "基金": ASSET_TYPE_FUND,
            "指数": ASSET_TYPE_INDEX,
            "ETF": ASSET_TYPE_ETF
        }
        
        # 资产搜索
        asset_input = st.text_input(
            f"输入{asset_type}代码或名称", 
            placeholder=f"如: {'000001 或 平安银行' if asset_type=='股票' else '代码或名称'}"
        )
        
        selected_asset = None
        
        if asset_input:
            try:
                # 获取对应资产类型的列表
                asset_list = repository.get_asset_list(asset_type_map[asset_type])
                
                if asset_list is not None and not asset_list.empty:
                    filtered_assets = asset_list[
                        (asset_list['code'].str.contains(asset_input)) | 
                        (asset_list['name'].str.contains(asset_input))
                    ]
                    
                    if not filtered_assets.empty:
                        selected_index = st.selectbox(
                            f"选择{asset_type}:",
                            options=filtered_assets.index,
                            format_func=lambda x: f"{filtered_assets.loc[x, 'code']} - {filtered_assets.loc[x, 'name']}"
                        )
                        
                        if selected_index is not None:
                            selected_asset = {
                                'code': filtered_assets.loc[selected_index, 'code'],
                                'name': filtered_assets.loc[selected_index, 'name'],
                                'type': asset_type_map[asset_type]
                            }
                    else:
                        st.warning(f"未找到匹配的{asset_type}，请重新输入")
                else:
                    st.warning(f"无法获取{asset_type}列表")
            except Exception as e:
                st.error(f"搜索{asset_type}时出错: {str(e)}")
        
        # 如果没有选择资产，则返回None
        if not selected_asset:
            return None
        
        # 分析类型选择 - 根据资产类型显示不同选项
        if asset_type == "股票":
            analysis_type = st.radio(
                "选择分析类型:",
                ["估值分析", "财务分析", "技术分析", "资金流向分析", "综合分析"]
            )
        elif asset_type == "期货":
            analysis_type = st.radio(
                "选择分析类型:",
                ["技术分析", "持仓分析", "综合分析"]
            )
        elif asset_type == "期权":
            analysis_type = st.radio(
                "选择分析类型:",
                ["希腊字母分析", "波动率分析", "综合分析"]
            )
        elif asset_type in ["基金", "ETF"]:
            analysis_type = st.radio(
                "选择分析类型:",
                ["净值分析", "持仓分析", "业绩分析", "综合分析"]
            )
        elif asset_type == "指数":
            analysis_type = st.radio(
                "选择分析类型:",
                ["技术分析", "成分股分析", "综合分析"]
            )
        
        # 时间范围选择
        time_range = st.selectbox(
            "选择时间范围:",
            ["1个月", "3个月", "6个月", "1年", "3年", "5年", "全部"],
            index=3  # 默认选择1年
        )
        
        # 高级设置折叠面板
        with st.expander("高级设置"):
            # 复权方式
            adjust_method = st.selectbox(
                "复权方式:",
                list(ADJUST_METHODS.keys()),
                index=0
            )
            
            # 数据频率
            data_period = st.selectbox(
                "数据频率:",
                list(DATA_PERIODS.keys()),
                index=0
            )
        
        # 执行分析按钮
        analyze_clicked = st.button("执行分析")
        
        # 返回用户选择的参数
        if analyze_clicked:
            return {
                "asset_code": selected_asset['code'],
                "asset_name": selected_asset['name'],
                "asset_type": selected_asset['type'],
                "analysis_type": analysis_type,
                "time_range": time_range,
                "adjust_method": ADJUST_METHODS[adjust_method],
                "data_period": DATA_PERIODS[data_period],
                "analyze_clicked": True
            }
        
        return None